package com.cxx.purchasecharge.core.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class DateUtils
{
    private static final Logger logger = Logger.getLogger (DateUtils.class);

    public static final String DATE_PATTERN = "yyyy-MM-dd";
    public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_TIME_NO_SECOND_PATTERN = "yyyy-MM-dd HH:mm";

    public static String date2String (Date date, String sformat)
    {
        String dateStr = null;
        if (null != date)
        {
            try
            {
                DateFormat sdf = new SimpleDateFormat (sformat);
                dateStr = sdf.format (date);
            }
            catch (Exception e)
            {
                logger.error (e.getMessage ());
            }
        }
        return dateStr;
    }

    public static Date string2Date (String dateString, String sformat)
    {
        DateFormat sdf = new SimpleDateFormat (sformat);
        Date date = null;
        if (!StringUtils.isBlank (dateString))
        {
            try
            {
                date = sdf.parse (dateString);
            }
            catch (ParseException e)
            {
                logger.error (e.getMessage ());
            }
        }
        return date;
    }
    
    /**
     * 得到几天前的时间
     * 
     * @param d
     * @param day
     * @return
     */
    public static Date getDateBefore (Date d, int day)
    {
        Calendar now = Calendar.getInstance ();
        now.setTime (d);
        now.set (Calendar.DATE, now.get (Calendar.DATE) - day);
        return now.getTime ();
    }

    /**
     * 得到几天后的时间
     * 
     * @param d
     * @param day
     * @return
     */
    public static Date getDateAfter (Date d, int day)
    {
        Calendar now = Calendar.getInstance ();
        now.setTime (d);
        now.set (Calendar.DATE, now.get (Calendar.DATE) + day);
        return now.getTime ();
    }

    public static void main (String[] args)
    {
        Date d = new Date ();
        System.out.println (date2String (d, DATE_TIME_PATTERN));
        Date date = new Date (d.getTime () + (30 * 24 * 3600 * 1000));
        System.out.println (date2String (date, DATE_PATTERN));

        Calendar calendar = Calendar.getInstance ();
        calendar.setTimeInMillis (d.getTime ());
        calendar.set (Calendar.DATE, calendar.get (Calendar.DATE) + 30);
        System.out.println (date2String (calendar.getTime (), DATE_PATTERN));

        System.out.println (string2Date ("03/31/2014 00:00:00", DATE_TIME_PATTERN));
        System.out.println (string2Date ("03/31/2014 23:59:59", DATE_TIME_PATTERN));
    }
}
